package com.taptech.doufu.ui.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.taptech.doufu.constant.HomePageType;
import com.taptech.doufu.ui.view.viewflow.view.CircleFlowIndicator;
import com.taptech.doufu.ui.view.viewflow.view.HomeViewFlow;
import com.taptech.doufu.ui.view.TTHomeViewPager;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.adapter.DFMemberAdapter;
import com.taptech.doufu.bean.DFHomeBannerBean;
import com.taptech.doufu.bean.novel.VipTopicBean;
import com.taptech.doufu.util.CommonUtils;
import com.taptech.doufu.listener.ToUpOrDownable;
import com.taptech.doufu.presenter.home.VipBannerPresenter;
import com.taptech.doufu.presenter.home.VipTopicPresenter;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.ui.view.HomeBannerImageAdapter;
import com.taptech.doufu.ui.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 会员专区
 */
public class DFMemberFragment extends HomeBaseFragment
        implements PullToRefreshListView.OnLoadAndRefreshListener,
        VipBannerPresenter.OnHomeBannerView, VipTopicPresenter.OnHomeTopicView {
    private PullToRefreshListView listView;
    private HomeViewFlow viewFlow;
    private HomeBannerImageAdapter viewFlowAdapter;//轮播图适配器
    private CircleFlowIndicator flowIndicator;
    private List<DFHomeBannerBean> bannerList;
    private List<VipTopicBean> contentAdaList;
    private TTHomeViewPager viewPager;//父类所含有的viewpage，用来控制图片轮转时，触摸事件不回传给父类
    private DFMemberAdapter listAda;//滑动适配器
    private ImageView ivTop;
    private View rootView;

    private boolean isUseCache = true;
    private VipTopicPresenter topicPresenter;
    private VipBannerPresenter bannerPresenter;

    //用于统计用户点击的卡片是在首页的那个页面---当前是会员页面   1是彩虹  3 是言情
    public static String HOME_MEMBER_SEX_TYPE = "-1";



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_dfnovel, null);
            initPresenter();
            initsView(rootView);
            loadCache();
            getDataFromNet();
        }
        return rootView;
    }

    private void initPresenter() {
        topicPresenter = new VipTopicPresenter(getActivity(),this);
        bannerPresenter = new VipBannerPresenter(getActivity(),this);
    }

    private void loadCache() {
        if (bannerPresenter != null) {
            bannerPresenter.loadVipBannerCache();
        }
        if (topicPresenter != null) {
            topicPresenter.loadVipTopicCache();
        }

    }


    private void initsView(View rootView) {
        listView = (PullToRefreshListView) rootView.findViewById(R.id.fragment_dfnovel_list);
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        listView.setRefreshable(true);
        listView.setOnLoadAndRefreshListener(this);
        listView.setMoveListener(new ToUpOrDownable() {
            @Override
            public void moveToUp() {
                ivTop.setVisibility(View.INVISIBLE);
                setToTopVisible(false);
            }

            @Override
            public void moveToDown(int firstVisiblePos) {
                if (firstVisiblePos > 2) {
                    ivTop.setVisibility(View.VISIBLE);
                    setToTopVisible(true);
                }else{
                    ivTop.setVisibility(View.INVISIBLE);
                }
            }
        });
        ivTop = (ImageView) rootView.findViewById(R.id.fragment_dfnovel_upTop);
        ivTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToTop();
            }
        });
        initsListViewHeadView();
    }
    public void scrollToTop() {
        if (listView != null) {
            listView.setSelection(0);
        }
        if (ivTop != null) {
            ivTop.setVisibility(View.INVISIBLE);

        }
    }

    private boolean toTopButtonIsShow = false;

    private void setToTopVisible(boolean visibleAnimation) {
        ObjectAnimator objectAnimators = null;
        AnimatorSet animatorSet = new AnimatorSet();
        if (visibleAnimation) {
            //出现动画
            if (!toTopButtonIsShow) {
                objectAnimators = ObjectAnimator.ofFloat(ivTop, "translationY", ScreenUtil.getScreenHeight(this.getActivity()), 0);
            }
            toTopButtonIsShow = true;
        } else {
            //隐藏动画
            if (toTopButtonIsShow) {
                objectAnimators = ObjectAnimator.ofFloat(ivTop, "translationY", 0, ScreenUtil.getScreenHeight(this.getActivity()) - ivTop.getMeasuredHeight());
            }
            toTopButtonIsShow = false;
        }
        if (objectAnimators != null) {
            animatorSet.setDuration(500);
            animatorSet.playTogether(objectAnimators);
            animatorSet.start();
        }

    }



    /**
     * request server
     */
    private void getDataFromNet() {
        if (listView.getLoadCompleteImg() != null) {
            listView.getLoadCompleteImg().setVisibility(View.GONE);
        }
        listView.setFull(false);
        listView.setLoadmoreable(false);
        if (topicPresenter != null) {
            topicPresenter.getVipTopic(isUseCache);
        }
        if (bannerPresenter != null) {
            bannerPresenter.getHomeNovelBanner(isUseCache);
        }
    }
    /**
     * 装 headView,包    ，下面
     */
    private void initsListViewHeadView() {

        contentAdaList = new ArrayList<>();
        listAda = new DFMemberAdapter(getActivity(), contentAdaList);
        listView.setAdapter(listAda);
    }


    View homeTopEnterView;

    private void addHeadView() {
        if (homeTopEnterView == null) {
            homeTopEnterView = LayoutInflater.from(getActivity()).inflate(R.layout.dfhome_viewflow_member, null);
            viewFlow = (HomeViewFlow) homeTopEnterView.findViewById(R.id.dfhome_exchange_viewflow);
            viewFlow.setLayoutParams(new RelativeLayout.LayoutParams(ScreenUtil.getScreenWidth(getActivity()), (int) (ScreenUtil.getScreenWidth(getActivity())/1.5)));
            flowIndicator = (CircleFlowIndicator) homeTopEnterView.findViewById(R.id.dfhome_ad_indicator);
            flowIndicator.setVisibility(View.VISIBLE);
            listView.addHeaderView(homeTopEnterView);
        }
    }

    @Override
    public synchronized void onRefresh() {
        listView.setLoadmoreable(false);
        //重新加载数据
        isUseCache = false;
        getDataFromNet();
    }


    @Override
    public synchronized void loadMore() {
        if (listView.isLoadmoreable()) {
            if (!CommonUtils.isNetWorkConnected(getActivity())) {
                listView.loadMoreComplete();
                listView.setLoadmoreable(true);
                return;
            }

        }
    }


    private void initFlowData() {

        try {
            if (viewFlow != null && bannerList != null) {
                viewFlowAdapter = new HomeBannerImageAdapter(bannerList, getActivity(),HomePageType.NEW_VIP);
                viewFlow.setAdapter(viewFlowAdapter);
                viewFlow.setmSideBuffer(bannerList.size());// 实际图片张数为size大小
                viewFlow.setTimeSpan(5000);// 图片切换时间间隔
                if (viewPager != null) {
                    viewFlow.setViewPage(viewPager);
                }
                flowIndicator.setViewFlow(viewFlow);
                viewFlow.setFlowIndicator(flowIndicator);
                if (bannerList.size() > 1) {
                    viewFlow.startAutoFlowTimer(); // 启动自动播放
                }
            } else {
                viewFlowAdapter.setData(bannerList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setViewPager(TTHomeViewPager mViewPager) {
        this.viewPager = mViewPager;
    }


    @Override
    public void fetchData() {

    }


    @Override
    public void onTopicNext(List<VipTopicBean> list, boolean isCache) {
        contentAdaList = list;
        if (listAda != null && isCache) {
            listAda.refrushList(contentAdaList);
        }else{
            listAda = new DFMemberAdapter(getActivity(), contentAdaList);
            listView.setAdapter(listAda);
        }
        onRefreshComplete();
    }

    @Override
    public void onTopicError() {
        onRefreshComplete();
    }


    private void onRefreshComplete() {
        /**
         * 刷新动画做延迟处理
         */
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                    Activity activity = getActivity();
                    if (activity != null) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (listView != null) {
                                    listView.onRefreshComplete();
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }



    @Override
    public void onBannerNext(List<DFHomeBannerBean> list, boolean isCache) {
        if (list != null && list.size()>0) {
            addHeadView();
            bannerList = list;
            initFlowData();
        }
    }


}
